package com.jjmmbb.stockdiary;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.jjmmbb.stockdiary.ex.DialogLoading;
import com.jjmmbb.stockdiary.ex.HKDialog;

public class BakActivity extends BaseActivity implements OnClickListener {
	Button bt_bak, bt_txt, bt_res;

	DialogLoading dialogLoading;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_OPTIONS_PANEL);
		setContentView(R.layout.bak);
		bt_bak = (Button) findViewById(R.id.opt_bakRes_bak);
		bt_txt = (Button) findViewById(R.id.opt_bakRes_txt);
		bt_res = (Button) findViewById(R.id.opt_bakRes_res);

		bt_bak.setOnClickListener(this);
		bt_txt.setOnClickListener(this);
		bt_res.setOnClickListener(this);
		ini();
	}

	void ini() {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.opt_bakRes_bak:
			IOType = 1;
			break;
		case R.id.opt_bakRes_txt:
			IOType = 2;
			break;
		case R.id.opt_bakRes_res:
			IOType = 3;
			break;
		default:
			break;
		}
		TaskIO task = new TaskIO();
		task.execute();
	}

	int IOType = 1; // 1:备份,2:备份到文本,3:还原
	boolean isIOSuccess = false;

	private class TaskIO extends AsyncTask<String, Integer, String> {
		@Override
		protected void onPreExecute() {
			showDialogLoading();
			super.onPreExecute();
		}

		protected String doInBackground(String... params) {
			switch (IOType) {
			case 1:
				isIOSuccess = UtilFile.saveToFile(ap.c.itemManager);
				break;
			case 2:
				isIOSuccess = UtilFile.saveToFile_txt(ap.c.itemManager);
				break;
			case 3:
				isIOSuccess = UtilFile.restoreFromFile(ap.c.itemManager);
				break;
			default:
				break;
			}
			return null;
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			cancelDialogLoading();
			String msg = "";
			if (isIOSuccess) {
				switch (IOType) {
				case 1:
					msg = getString(R.string.bak_success_bak);
					break;
				case 2:
					msg = getString(R.string.bak_success_txt);
					break;
				case 3:
					msg = getString(R.string.bak_success_res);
					break;
				default:
					break;
				}
				HKDialog dialog = new HKDialog(BakActivity.this, msg) {
					protected void bt1Click() {
						super.bt1Click();
						BakActivity.this.finish();
					};
				};
				dialog.show();
			} else {
				HKDialog dialog = new HKDialog(BakActivity.this,
						getString(R.string.bak_failure));
				dialog.show();
			}
		}
	}

	void showDialogLoading() {
		dialogLoading = new DialogLoading(this);
		dialogLoading.show();
	}

	void cancelDialogLoading() {
		dialogLoading.hide();
	}

}
